package org.farm.product.domain.chain.handler;

import lombok.extern.slf4j.Slf4j;
import org.farm.common.response.enums.BusinessException;
import org.farm.common.response.enums.ResultCodeEnums;
import org.farm.product.domain.bo.ProductSpuBo;
import org.farm.product.domain.bo.ProductSpuDetailBo;
import org.farm.product.domain.convert.ProductSpuDetailBoConvert;
import org.farm.product.infra.basic.entity.ProductSpuDetail;
import org.farm.product.infra.basic.service.ProductSpuDetailService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2025/4/23
 * @description
 */
@Slf4j
@Order(2)
@Component
public class ProductSpuDetailHandler implements ProductSpuHandler{

    private final ProductSpuDetailService productSpuDetailService;

    private ProductSpuHandler nextHandler;

    public ProductSpuDetailHandler(ProductSpuDetailService productSpuDetailService) {
        this.productSpuDetailService = productSpuDetailService;
    }

    @Override
    public void handler(ProductSpuBo productSpuBo) {
        log.info("ProductSpuDetailHandler start handle");
        ProductSpuDetailBo productSpuDetail = productSpuBo.getProductSpuDetail();
        if (Objects.isNull(productSpuDetail)) {
            return;
        }
        // TODO: 2025/4/23 处理商品详情信息
        ProductSpuDetail detail = ProductSpuDetailBoConvert.INSTANCE.convertBoToEntity(productSpuDetail);
        detail.setSpuId(productSpuBo.getId());
        boolean save = productSpuDetailService.save(detail);
        if (!save) {
            throw new BusinessException(ResultCodeEnums.BUSINESS_ERROR, "ProductSpuDetailHandler save error");
        }
        log.info("ProductSpuDetailHandler end handle");
        if (Objects.nonNull(nextHandler)) {
            nextHandler.handler(productSpuBo);
        }
    }

    @Override
    public void setNextHandler(ProductSpuHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    @Override
    public ProductSpuHandler getNextHandler() {
        return this.nextHandler;
    }
}
